const crypto = require('crypto');
module.exports = app =>{
    const { INTEGER, STRING, DATE, ENUM, TEXT } = app.Sequelize;

    const User = app.model.define('user', {
        id: {
          type: INTEGER(20),
          primaryKey: true,
          autoIncrement: true
        },
        number: {
          type: STRING(30),
          allowNull: true,
          defaultValue: '',
          comment: '学号',
          unique: true
        },
        username: {
          type: STRING(30),
          allowNull: false,
          defaultValue: '',
          comment: '用户名',
          unique: true
        },
        password: {
          type: STRING,
          allowNull: false,
          defaultValue: '',
          comment: "密码",
          set(val){
            const hmac = crypto.createHash("sha256", app.config.crypto.secret);
            hmac.update(val);
            let hash = hmac.digest("hex");
            this.setDataValue('password', hash);
          }
        },
        openid: {
          type: STRING,
          allowNull: true,
          defaultValue: '',
          comment: 'openid'
        },
        class_id: {
          type: INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: "年级id",
        },
        avatar: {
            type: STRING,
            allowNull: true,
            defaultValue: '',
            comment: '头像'
          },
          coin: {
            type: INTEGER,
            allowNull: false,
            defaultValue: 0,
            comment: '金币'
          },
        created_time: {
          type:DATE,
          get(){
             return app.formatTime(this.getDataValue('created_time'))
          }
        },
        updated_time: DATE,
    });

    User.associate = function() {
      app.model.User.hasMany(app.model.Score, { foreignKey: 'user_id' });

     // 与Class存在多对一关系，所以使用belongsTo()
     app.model.User.belongsTo(app.model.Class, {foreignKey: 'class_id', targetKey: 'id'});
     
    // 与Branch存在多对多关系，使用belongsToMany()
      app.model.User.belongsToMany(app.model.Branch, {
        through: app.model.BranchUser,
        foreignKey: 'user_id',
        otherKey: 'branch_id'
    });


    };

    return User;
}